package com.zenithmind.chat.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * WebSocket握手拦截器
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Component
public class WebSocketInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                 WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        
        // 从请求参数中获取用户ID和token
        String query = request.getURI().getQuery();
        if (StringUtils.hasText(query)) {
            String[] params = query.split("&");
            for (String param : params) {
                String[] keyValue = param.split("=");
                if (keyValue.length == 2) {
                    String key = keyValue[0];
                    String value = keyValue[1];
                    
                    if ("userId".equals(key)) {
                        attributes.put("userId", value);
                    } else if ("token".equals(key)) {
                        attributes.put("token", value);
                    } else if ("groupId".equals(key)) {
                        attributes.put("groupId", value);
                    }
                }
            }
        }
        
        // 验证用户ID是否存在
        String userId = (String) attributes.get("userId");
        if (!StringUtils.hasText(userId)) {
            log.warn("WebSocket连接失败：缺少用户ID");
            return false;
        }
        
        // TODO: 验证token的有效性
        String token = (String) attributes.get("token");
        if (!StringUtils.hasText(token)) {
            log.warn("WebSocket连接失败：缺少token");
            return false;
        }
        
        // 记录连接信息
        String clientIp = getClientIp(request);
        attributes.put("clientIp", clientIp);
        
        log.info("WebSocket握手成功：用户ID={}, IP={}", userId, clientIp);
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                             WebSocketHandler wsHandler, Exception exception) {
        if (exception != null) {
            log.error("WebSocket握手后异常", exception);
        }
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIp(ServerHttpRequest request) {
        String xForwardedFor = request.getHeaders().getFirst("X-Forwarded-For");
        if (StringUtils.hasText(xForwardedFor)) {
            return xForwardedFor.split(",")[0].trim();
        }
        
        String xRealIp = request.getHeaders().getFirst("X-Real-IP");
        if (StringUtils.hasText(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddress() != null ? 
               request.getRemoteAddress().getAddress().getHostAddress() : "unknown";
    }
}
